package cn.mothin.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mothin.bean.easyui.DataContent;
import cn.mothin.bean.system.DictionaryTreeData;
import cn.mothin.dao.DictionaryItemDao;
import cn.mothin.dao.DictionaryTypeDao;
import cn.mothin.entity.DictionaryItem;
import cn.mothin.entity.DictionaryType;
import cn.mothin.frame.bean.ActionResult;
import cn.mothin.frame.core.base.BaseService;
import cn.mothin.frame.help.UniqueCode;
import cn.mothin.frame.util.StringUtil;
import cn.mothin.vo.system.DictionaryForm;

import com.google.gson.Gson;

@Service
public class DictionaryService extends BaseService {
    @Autowired
    private DictionaryTypeDao dictionaryTypeDao;
    @Autowired
    private DictionaryItemDao dictionaryItemDao;

    /**
     * 查询字典类型
     * 
     * @param dictionaryForm
     * @return
     */
    public String queryTypes(DictionaryForm dictionaryForm) {
        String sql = "SELECT id,name,innate,treeStructure,memo FROM dictionary_type WHERE allowConfig=TRUE AND deleted<>TRUE";
        return dictionaryTypeDao.queryJson(dictionaryForm, sql);
    }

    /**
     * 根据字典类型id查看详情
     * 
     * @param dictionaryForm
     */
    public int queryByTypeId(DictionaryForm dictionaryForm) {
        String dictionaryTypeId = dictionaryForm.getDictionaryType().getId();
        if (StringUtil.isNullOrEmpty(dictionaryTypeId)) {
            return 1;
        }
        DictionaryType dictionaryType = dictionaryTypeDao.get(dictionaryTypeId);
        if (dictionaryType == null) {
            return 1;
        }
        if (dictionaryType.isDeleted()) {
            return 2;
        }
        dictionaryForm.setDictionaryType(dictionaryType);
        return 0;
    }

    /**
     * 添加新的字典类型
     * 
     * @param dictionaryForm
     * @return
     */
    public ActionResult addType(DictionaryForm dictionaryForm) {
        ActionResult result = ActionResult.getInstance();
        if (dictionaryTypeDao.checkExistedByName(dictionaryForm
                .getDictionaryType().getName())) {
            result.setOk(false);
            result.setMessage("相同名称的字典类型已存在");
        } else {
            String id = UniqueCode.make();
            DictionaryType dictionaryType = new DictionaryType();
            dictionaryType.setId(id);
            dictionaryType
                    .setName(dictionaryForm.getDictionaryType().getName());
            dictionaryType.setAllowConfig(true);
            dictionaryType.setInnate(false);
            dictionaryType.setTreeStructure(dictionaryForm.getDictionaryType()
                    .isTreeStructure());
            dictionaryType
                    .setMemo(dictionaryForm.getDictionaryType().getMemo());
            dictionaryTypeDao.save(dictionaryType);

            result.setValue(id);
        }
        return result;
    }

    /**
     * 修改字典类型 0：修改成功 1：被指定修改的字典类不存在 2：名称已使用
     * 
     * @param dictionaryForm
     * @return
     */
    public int updateType(DictionaryForm dictionaryForm) {
        DictionaryType dictionaryType = dictionaryTypeDao.get(dictionaryForm
                .getDictionaryType().getId());
        if (dictionaryType == null || dictionaryType.isDeleted()) {
            return 1;
        } else {
            if (dictionaryTypeDao.checkExistedByNameWithoutId(dictionaryForm
                    .getDictionaryType().getName(), dictionaryForm
                    .getDictionaryType().getId())) {
                return 2;
            } else {
                dictionaryType.setName(dictionaryForm.getDictionaryType()
                        .getName());
                dictionaryType.setMemo(dictionaryForm.getDictionaryType()
                        .getMemo());
                dictionaryType.setTreeStructure(dictionaryForm
                        .getDictionaryType().isTreeStructure());
                dictionaryTypeDao.update(dictionaryType);
            }
        }
        return 0;
    }

    /**
     * 删除指定字典类型
     * 
     * @param dictionaryForm
     * @return
     */
    public int deleteType(DictionaryForm dictionaryForm) {
        DictionaryType dictionaryType = dictionaryTypeDao.get(dictionaryForm
                .getDictionaryType().getId());
        if (dictionaryType == null || dictionaryType.isDeleted()) {
            return 1;
        }
        dictionaryType.setDeleted(true);
        dictionaryTypeDao.update(dictionaryType, "deleted");
        return 0;
    }

    private void addSub(DictionaryTreeData dictionaryTreeData) {
        List<DictionaryItem> dictionaryItems = dictionaryItemDao
                .querySubDictionaryItems(dictionaryTreeData.getId());
        for (int i = 0; i < dictionaryItems.size(); i++) {
            DictionaryItem dictionaryItem = dictionaryItems.get(i);
            DictionaryTreeData sub = new DictionaryTreeData();
            sub.setId(dictionaryItem.getId());
            sub.setMemo(dictionaryItem.getMemo());
            sub.setName(dictionaryItem.getName());
            sub.setNameDisplay(dictionaryItem.getNameDisplay());
            sub.setSystem(dictionaryItem.isInnate());
            addSub(sub);
            dictionaryTreeData.addChild(sub);
        }
    }

    /**
     * 查询字典项
     * 
     * @param dictionaryForm
     * @return
     */
    public String queryItems(DictionaryForm dictionaryForm) {
        List<DictionaryTreeData> list = new ArrayList<DictionaryTreeData>();
        DictionaryType dictionaryType = dictionaryTypeDao.get(dictionaryForm
                .getDictionaryType().getId());

        List<DictionaryItem> dictionaryItems = dictionaryItemDao
                .queryDictionaryItems(dictionaryForm.getDictionaryType()
                        .getId());
        for (int i = 0; i < dictionaryItems.size(); i++) {
            DictionaryItem dictionaryItem = dictionaryItems.get(i);
            DictionaryTreeData sub = new DictionaryTreeData();
            sub.setId(dictionaryItem.getId());
            sub.setMemo(dictionaryItem.getMemo());
            sub.setName(dictionaryItem.getName());
            sub.setNameDisplay(dictionaryItem.getNameDisplay());
            sub.setSystem(dictionaryItem.isInnate());
            if (dictionaryType.isTreeStructure()) {
                addSub(sub);
            }
            list.add(sub);
        }

        Gson gson = new Gson();
        return gson.toJson(list);
    }

    /**
     * 添加字典项
     * 
     * @param dictionaryForm
     * @return
     */
    public ActionResult addItem(DictionaryForm dictionaryForm) {
        ActionResult result = ActionResult.getInstance();
        DictionaryType type = dictionaryForm.getDictionaryType();
        DictionaryItem item = dictionaryForm.getDictionaryItem();
        if (dictionaryItemDao.checkExistedByName(type.getId(), item.getName(),
                item.getParentId())) {
            result.setOk(false);
            result.setMessage("此字典项已存在");
        } else {
            String id = UniqueCode.make();
            DictionaryItem dictionaryItem = new DictionaryItem();
            dictionaryItem.setId(id);
            dictionaryItem.setDictionaryTypeId(type.getId());
            dictionaryItem.setName(item.getName());
            dictionaryItem.setInnate(false);
            dictionaryItem.setNameDisplay(item.getNameDisplay());
            dictionaryItem.setMemo(item.getMemo());
            if (StringUtil.isNullOrEmpty(item.getParentId())) {
                dictionaryItem.setParentId(null);
            } else {
                dictionaryItem.setParentId(item.getParentId());
            }
            dictionaryItemDao.save(dictionaryItem);
            result.setValue(id);
        }
        return result;
    }

    /**
     * 查看字典项详情
     * 
     * @param dictionaryForm
     */
    public int queryItemById(DictionaryForm dictionaryForm) {
        String dictionaryItemId = dictionaryForm.getDictionaryItem().getId();
        if (StringUtil.isNullOrEmpty(dictionaryItemId)) {
            return 1;
        }
        DictionaryItem dictionaryItem = dictionaryItemDao.get(dictionaryItemId);
        if (dictionaryItem == null) {
            return 1;
        }
        if (dictionaryItem.isDeleted()) {
            return 2;
        }
        dictionaryForm.setDictionaryItem(dictionaryItem);
        return 0;
    }

    /**
     * 修改字典项
     * 
     * @param dictionaryForm
     *            0：修改完成； 1：不存在或者已删除； 2：名称已使用
     * @return
     */
    public int updateItem(DictionaryForm dictionaryForm) {
        DictionaryItem dictionaryItem = dictionaryItemDao.get(dictionaryForm
                .getDictionaryItem().getId());
        if (dictionaryItem == null || dictionaryItem.isDeleted()) {
            return 1;
        } else {
            DictionaryType type = dictionaryForm.getDictionaryType();
            DictionaryItem item = dictionaryForm.getDictionaryItem();
            if (dictionaryItemDao.checkExistedByNameWithoutId(type.getId(),
                    item.getName(), dictionaryItem.getParentId(), item.getId())) {
                return 2;
            } else {
                dictionaryItem.setName(item.getName());
                dictionaryItem.setNameDisplay(item.getNameDisplay());
                dictionaryItem.setMemo(item.getMemo());
                dictionaryItemDao.update(dictionaryItem);
            }
        }
        return 0;
    }

    /**
     * 删除字典项
     * 
     * @param dictionaryForm
     * @return
     */
    public int deleteItem(DictionaryForm dictionaryForm) {
        DictionaryItem dictionaryItem = dictionaryItemDao.get(dictionaryForm
                .getDictionaryItem().getId());
        if (dictionaryItem == null || dictionaryItem.isDeleted()) {
            return 1;
        }
        dictionaryItem.setDeleted(true);
        dictionaryItemDao.update(dictionaryItem, "deleted");
        return 0;
    }
    
    
    //------------------------------------------------------------------>>>
    //--------------------字典控件数据查询---------------------------------
    //------------------------------------------------------------------>>>
    /**
     * 
     * @param dataContent
     * @param selected
     * @return
     */
    private boolean addSub(DataContent dataContent,List<String> selected) {
        List<DictionaryItem> items =dictionaryItemDao.querySubDictionaryItems(dataContent.getId());
        for (int i = 0; i < items.size(); i++) {
            DictionaryItem item = items.get(i);
            DataContent sub = new DataContent();
            sub.setId(item.getId());
            sub.setText(item.getName());
            sub.setNameDisplay(item.getNameDisplay());
            if(selected.size()>0&&selected.contains(item.getId())){
                sub.setChecked(true);
                sub.setSelected(true);
            }
            addSub(sub,selected);
            dataContent.addChild(sub);
        }
        if(items.size()>0){
            return true;
        }
        return false;
    }
    
    public ActionResult queryForControl(DictionaryForm dictionaryForm) {
        ActionResult actionResult=ActionResult.getInstance();
        String type=dictionaryForm.getDictionaryType().getId();
        if(StringUtil.isNullOrEmpty(type)){
            actionResult.setOk(false);
            return actionResult;
        }
        
        boolean tree=false;
        List<String> selected=new ArrayList<String>();
        if(!StringUtil.isNullOrEmpty(dictionaryForm.getSelected())){
            String[] ss=dictionaryForm.getSelected().split(",");
            for(int i=0;i<ss.length;i++){
                selected.add(ss[i]);
            }
        }
        
        List<DataContent> list = new ArrayList<DataContent>();
        List<DictionaryItem> items = dictionaryItemDao.queryDictionaryItems(type);
        for (int i = 0; i < items.size(); i++) {
            DictionaryItem dictionaryItem = items.get(i);
            DataContent sub = new DataContent();
            sub.setId(dictionaryItem.getId());
            sub.setText(dictionaryItem.getName());
            sub.setNameDisplay(dictionaryItem.getNameDisplay());
            if(selected.size()>0&&selected.contains(dictionaryItem.getId())){
                sub.setChecked(true);
                sub.setSelected(true);
            }
            if(addSub(sub,selected)){
                if(!tree){
                    tree=true;
                }
            }
            list.add(sub);
        }
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("tree", tree);
        map.put("value", list);
        actionResult.setValue(map);
        
        return actionResult;
    }
    //<<<-------------------------------------------------------------------
    
}
